package com.hbusa.cotroller.image;

import com.hbusa.dto.TbPicture;
import com.hbusa.service.ImageService;
import com.hbusa.service.impl.ImageServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author XiaoXin
 * @date 2021/12/26 - 21:38
 */

@WebServlet("/admin/doUpload")
public class UploadServlet extends HttpServlet {
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ImageServiceImpl imageService = new ImageServiceImpl();
        List<TbPicture> tbPictures = imageService.queryAll();
        System.out.println(tbPictures);
        req.setAttribute("tbPictures", tbPictures);
        req.getRequestDispatcher("/admin/image.jsp").forward(req, resp);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        // 1. 判断请求是否为multipart请求
        if (!ServletFileUpload.isMultipartContent(req))
        {
            throw  new RuntimeException("当前请求不支持文件上传");
        }

        try {
            // 创建一个FileItem工厂
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            // 创建文件上传核心组件
            ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory);
            // 解析请求，获取到所有的item
            List<FileItem> fileItems = upload.parseRequest(req);
            // 遍历fileItems
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()) { // 若fileItem为普通表单项
                    String fieldName = fileItem.getFieldName();  // 获取表单项名称
                    String fileValue = fileItem.getString(fieldName); // 获取表单项的值
                    System.out.println("fileName:" + fieldName + " fileItem:" + fileValue);

                } else { // 若fileItem为文件表单项
                    String fileName = fileItem.getName(); // 获取原始名称
                    // 获取输入流，其中有上传文件的内容
                    InputStream fis = fileItem.getInputStream();
                    // 获取文件保存在服务器的路径
                    // 待解决
                    String path = "F:/NovelSystem/NovelSystemSource/src/main/webapp/static/images";
                    // 创建文件输出流
                    FileOutputStream fos = new FileOutputStream(new File(path, fileName));
                    // 将将输入流写入到输出流中
                    int copy = IOUtils.copy(fis, fos);
                    if (copy > 0) {
                        System.out.println("上传成功");
                        req.setAttribute("url", path + "/" + fileName);
                        HttpSession session = req.getSession();
                        String pictureId = (String) session.getAttribute("picture_id");
                        if (pictureId != null) {
                            req.getRequestDispatcher("doUpdate").forward(req, resp);
                        } else {
                            req.getRequestDispatcher("doAdd").forward(req, resp);
                        }
                    }
                }

            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        System.out.println("uploadServlet运行了");
    }
}
